/*

 Copyright 2012 Peter Dornbach.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
   
*/

package com.dornbachs.zebra.guitarear;

import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TableRow;
import android.widget.TextView;

public class PracticeActivity extends BaseActivity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.practice);

		_challenge = Challenge.getChallenge(this);
		_listenButton = (Button)findViewById(R.id.button_practice_listen);
		_listenButton.setOnClickListener(
				new View.OnClickListener() {
					public void onClick(View view) {
						if (_challenge.playChallenge()) {
							updateUI();
						}
					}
				});
		findViewById(R.id.button_practice_back).setOnClickListener(
				new View.OnClickListener() {
					public void onClick(View view) {
						finish();
					}
				});
		
		_pickTextView = (TextView) findViewById(R.id.textView_pick);
		_resultTextView = (TextView) findViewById(R.id.textView_result);
		_statsTextView = (TextView) findViewById(R.id.textView_stats);

		Object obj = getLastNonConfigurationInstance();
		if (obj == null) {
			initChallenge();
			_lastResultText = " ";
		} else {
			_lastResultText = (String)obj;
		}
		initChordButtons();
		updateUI();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
    AlertDialog dialog = null;
    switch(id) {
    case DIALOG_FINISHED_LEVEL_ID:
    	dialog = new AlertDialog.Builder(this).create();
    	dialog.setCancelable(false);
    	dialog.setButton(
    			AlertDialog.BUTTON_POSITIVE,
    			getString(R.string.button_ok),
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
              PracticeActivity.this.finish();
            }
          });
    	prepareDialog(dialog);
    	break;
    }
    return dialog;
  }
	
	@Override
	protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
    switch(id) {
    case DIALOG_FINISHED_LEVEL_ID:
    	prepareDialog((AlertDialog)dialog);
			break;
		}
	}

	@Override
	public Object onRetainNonConfigurationInstance() {
		return _lastResultText;
	}
	
	protected void prepareDialog(AlertDialog dialog) {
		int stringId = 0;
		if (_challenge.successLevel()) {
			_challenge.markSuccess();
			stringId = R.string.text_level_success;
		} else {
			stringId = R.string.text_level_fail;
		}
		dialog.setMessage(
				getString(
						stringId,
						getLocalNumStr(
								_challenge.numHits(),
								R.string.text_hits_singular,
								R.string.text_hits_plural),
						getLocalNumStr(
								_challenge.numMisses(),
								R.string.text_misses_singular,
								R.string.text_misses_plural),
						getLocalNumStr(
								_challenge.maxMisses(),
								R.string.text_misses_singular,
								R.string.text_misses_plural)));
	}
			
	private void initChordButtons() {
		final boolean enabled = _challenge.hasPlayedChallenge();
		ViewGroup layout = (ViewGroup) findViewById(R.id.linearLayout_chords);
		layout.removeAllViews();

		List<String> candidates = _challenge.getCandidates();
		final int numRows =
				(candidates.size() + MAX_CHORDS_PER_ROW - 1) /
				MAX_CHORDS_PER_ROW;
		final int numRowsWithFewerColumns =
				(candidates.size() + MAX_CHORDS_PER_ROW - 2) /
				(MAX_CHORDS_PER_ROW - 1);
		final int chordsPerRow = (
				numRows == numRowsWithFewerColumns ? 
				MAX_CHORDS_PER_ROW - 1 :
				MAX_CHORDS_PER_ROW);
		
		TableRow row = null;
		for (int i = 0; i < candidates.size(); ++i) {
			if (i % chordsPerRow == 0) {
				row = addTableRow(layout);
			}
			Button button = addButton(row, candidates.get(i));
			button.setEnabled(enabled);
			button.setOnClickListener(_tryListener);
		}
	}
	
	private void enableChordButtons() {
		final boolean enabled = _challenge.hasPlayedChallenge();
		ViewGroup layout = (ViewGroup) findViewById(R.id.linearLayout_chords);
		for (int i = 0; i < layout.getChildCount(); ++i) {
			View v = layout.getChildAt(i);
			if (v instanceof TableRow) {
				TableRow row = (TableRow)v;
				for (int j = 0; j < row.getChildCount(); ++j) {
					View v2 = row.getChildAt(j);
					if (v2 instanceof Button) {
						v2.setEnabled(enabled);
					}
				}
			}
		}
	}

	private TableRow addTableRow(ViewGroup parent) {
		int idx = parent.getChildCount();
		getLayoutInflater().inflate(R.layout.chord_row, parent);
		TableRow row = (TableRow)parent.getChildAt(idx);
		return row;
	}

	private Button addButton(ViewGroup parent, String label) {
		int idx = parent.getChildCount();
		getLayoutInflater().inflate(R.layout.chord_button, parent);
		Button button = (Button)parent.getChildAt(idx);
		button.setText(label);
		return button;
	}

	private void initChallenge() {
		_challenge.nextChallenge(MAX_CHORDS);
	}

	private void updateUI() {
		if (_challenge.hasPlayedChallenge()) {
			_listenButton.setText(R.string.button_practice_again);
		} else {
			if (_challenge.hasMoreThanOneChord()) {
				_listenButton.setText(R.string.button_practice_new_riff);
			} else {
				_listenButton.setText(R.string.button_practice_new_chord);
			}
		}
		if (_challenge.hasMoreThanOneChord()) {
			switch (_challenge.currentChord()) {
			case 0: 
				_pickTextView.setText(R.string.text_practice_pick_1);
				break;
			case 1: 
				_pickTextView.setText(R.string.text_practice_pick_2);
				break;
			case 2: 
				_pickTextView.setText(R.string.text_practice_pick_3);
				break;
			default: 
				_pickTextView.setText(R.string.text_practice_pick_4);
				break;
			}
		} else {
			_pickTextView.setText(R.string.text_practice_pick_one);
		}
		enableChordButtons();
		_resultTextView.setText(_lastResultText);
		String statsText = getString(
				R.string.text_practice_stats,
				_challenge.numHits(),
				_challenge.numMisses());
		_statsTextView.setText(statsText);
	}
	
	private View.OnClickListener _tryListener = new View.OnClickListener() {
		public void onClick(View v) {
			Button button = (Button)v;
			String guess = button.getText().toString();
			boolean played = _challenge.playCandidate(guess);
			if (_challenge.tryCandidate(guess)) {
				if (_challenge.hasMoreChords()) {
					_lastResultText = getString(R.string.text_practice_correct);
				} else {
					if (_challenge.hasMoreThanOneChord()) {
						_lastResultText = getString(R.string.text_practice_all_correct);
					} else {
						_lastResultText = getString(R.string.text_practice_correct);
					}
					if (_challenge.finishedLevel()) {
						showDialog(DIALOG_FINISHED_LEVEL_ID);
					} else {
						initChallenge();
						initChordButtons();
					}
				}
			} else {
				if (played) {
					_lastResultText = getString(
									R.string.text_practice_sounds_like,
									guess);
				} else {
					_lastResultText = getString(R.string.text_practice_try_again);
				}
			}
			updateUI();
		}
	};

	private final static int DIALOG_FINISHED_LEVEL_ID = 1;
	
	private final static int MAX_CHORDS_PER_ROW = 4;
	private final static int MAX_CHORDS_ROW = 3;
	private final static int MAX_CHORDS = MAX_CHORDS_PER_ROW * MAX_CHORDS_ROW;
	
	private Challenge _challenge;
	private String _lastResultText;
	
	private Button _listenButton;
	private TextView _pickTextView;
	private TextView _resultTextView;
	private TextView _statsTextView;
}
